package com.lj.ljminsu.detail.controller;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.lj.ljminsu.detail.bean.JsonResultVO;
import com.lj.ljminsu.detail.bean.OrderInfo;
import com.lj.ljminsu.detail.dao.UserOrderDao;
import com.lj.ljminsu.detail.service.UserOrderService;


import io.goeasy.GoEasy;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("order")
public class OrderController {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private UserOrderService userOrderService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Resource
    private UserOrderDao userOrderDao;
    @RequestMapping("{houseId}")
    public String price(@PathVariable("houseId") Integer houseId){
        System.out.println("houseId:"+houseId);

        String s = restTemplate.getForObject("http://house-server/detail/houseStatus?houseId="+houseId, String.class);
        System.out.println(s);
        return s;
    }
    //抢购,直接拉取付款页
    @RequestMapping("qg")
    public JsonResultVO qg(String start, String houseId){
        //利用redis完成秒杀
        //高并发下,查看房东存入redis的key,这个key应该是有时间限制的,value,1#2019-08-02,5,对应houseId+date,num
        String key = houseId+"#"+start;
        JsonResultVO resultVO = new JsonResultVO();
        JsonResultVO vo = (JsonResultVO) stringRedisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.watch(key);//锁住house
                //获取对应的房间数
                String num = (String) redisOperations.boundValueOps(key).get();
                Integer houseNum = Integer.parseInt(num);
                //判断房间数是否大于0
                if (houseNum <= 0) {
                    //没房了,返回
                    resultVO.setFlag(0);
                    resultVO.setMsg("少侠晚来一步,房已经被抢光了");
                    return resultVO;
                }
                //有房,房数减一
                houseNum--;
                //放入redis
                redisOperations.boundValueOps(key).set(String.valueOf(houseNum));
                redisOperations.multi();
                //利用mq完成房屋数量减少

                resultVO.setMsg("恭喜!抢购成功");
                resultVO.setFlag(1);
                return resultVO;
            }
        });
        System.out.println(vo);
        return vo;
    }
    //普通订购,提交订单
    @RequestMapping("dg")
    public JsonResultVO dg(@RequestBody OrderInfo orderInfo){
        System.out.println(orderInfo);
        JsonResultVO resultVO = new JsonResultVO();
        //添加对应的订单表信息,默认state=0,未付款..,当前payTime是订单生成时间(便于页面计时)
        try {

            String codeUrl = userOrderService.updateOrder(orderInfo);
            resultVO.setMsg(codeUrl);
            resultVO.setFlag(1);
            return resultVO;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //跳转微信支付
        resultVO.setFlag(0);
        resultVO.setMsg("下单失败...");
        return resultVO;
    }
    //微信回调
    //受到微信的消息,需要回应
    @RequestMapping("wxnotify")
    public void wxNotify(HttpServletRequest request,HttpServletResponse response){
        System.out.println("支付成功");
        //接受微信信息
        try {
            ServletInputStream is = request.getInputStream();
            StringBuilder stringBuilder = new StringBuilder();
            byte[] byt = new byte[8192];
            int len = 0;
            while ((len=is.read(byt)) != -1){
                stringBuilder.append(new String(byt,0,len));
            }
            //微信发送的支付成功的消息,里面包含了订单的相关信息
            System.out.println(stringBuilder.toString());
            //利用mq给商家发送提醒,修改商品
            jmsMessagingTemplate.convertAndSend("updateHouse","房东,有人付款了!!");
            //goeasy跳转网页
            GoEasy goEasy = new GoEasy("https://rest-hangzhou.goeasy.io", "BC-37062195321d425da33335e69cbda0b8");
            goEasy.publish("ljpay", "success");
            //回复微信,这边操作完成,真正收钱
            response.getWriter().println("<xml>\n" +
                    "   <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>\n" +
                    "   <mch_id><![CDATA[10000100]]></mch_id>\n" +
                    "   <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>\n" +
                    "   <openid><![CDATA[oUpF8uMuAJO_M2pxb1Q9zNjWeS6o]]></openid>\n" +
                    "   <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>\n" +
                    "   <result_code><![CDATA[SUCCESS]]></result_code>\n" +
                    "   <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>\n" +
                    "   <trade_type><![CDATA[JSAPI]]></trade_type>\n" +
                    "</xml>");
        } catch (Exception e) {
            e.printStackTrace();
        }



    }
    //获取微信支付二维码
    @RequestMapping("code")
    public void qrcode(HttpServletResponse response,String url) throws URISyntaxException, IOException {
        //二维码需要包含的文本内容
        String uri = url;
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(uri, BarcodeFormat.QR_CODE, 200, 200, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
            System.out.println("创建二维码完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取订单
    @RequestMapping("payTime")
    public String payTime(String userId,String houseId){
        System.out.println("userId:"+userId+",houseId:"+houseId);
        String s = userOrderDao.queryPayTime(userId, houseId);
        return s;
    }

}
